﻿layui.use(['form', 'layer'], function () {
    var form = layui.form;
    var layer = layui.layer;
    var $ = layui.$;

    // 提交事件
    form.on('submit(demo1)', function (data) {
        var formData = new FormData($(data.form)[0]);
        var jsonData = {};

        // 将 FormData 对象的数据转换为 JSON 格式
        formData.forEach(function (value, key) {
            jsonData[key] = value;
        });

        // 发起Ajax请求更新数据
        $.ajax({
            url: 'http://10.31.60.18:8000//BeginningSetRout/api/Beginning/BeginninUpdate',
            type: 'PUT', // PUT请求
            data: JSON.stringify(jsonData), // 将数据转换为JSON格式
            contentType: 'application/json',
            success: function (response) {
                if (response.code == 200) {
                    layer.msg(response.msg, { icon: 1 });
                    setTimeout(function () {
                        location.href = '/Beginning/SpermatophoreShow';
                    }, 1000)
                } else {
                    layer.msg(response.msg, { icon: 2 });
                }
            },
            error: function (xhr, status, error) {
                console.error('Error occurred while updating data:', error);
                layer.alert('数据修改失败，请重试', {
                    title: '提示'
                });
            }
        });

        return false; // 阻止默认 form 提交
    });

    // 自定义函数，用于获取URL参数
    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    // 获取用户信息并反填到表单中
    function getUserInfo() {
        var BeginningId = getUrlParam('BeginningId');

        $.ajax({
            url: `http://10.31.60.18:8000/BeginningGetRout/api/BeginningRead/BeginningBackfill?BeginningId=${BeginningId}`,
            type: 'GET',
            success: function (response) {
                if (response.code === 200) {
                    var data = response.data;
                    $("#earNumber").val(data.earNumber);
                    $("#buildings").val(data.buildings);
                    $("#columns").val(data.columns);
                    $("#sheepNumber").val(data.sheepNumber);
                    $("#weight").val(data.weight);
                    $("#beginningId").val(data.beginningId);
                    $("#species").val(data.species);

                    // 重新渲染layui表单
                    // form.render();
                } else {
                    console.log('Failed to fetch data. Server response:', response);
                }
            },
            error: function (xhr, status, error) {
                console.error('Error occurred while fetching data:', error);
            }
        });
    }

    $(function () {
        getUserInfo();
    })
});